package com.sync.platform.controller;

import com.sync.platform.common.Result;
import com.sync.platform.entity.DatabaseConfig;
import com.sync.platform.entity.RestoreTask;
import com.sync.platform.service.DatabaseConfigService;
import com.sync.platform.service.RestoreTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Database restore controller
 */
@Controller
@RequestMapping("/restore")
public class DatabaseRestoreController {

    private static final Logger logger = LoggerFactory.getLogger(DatabaseRestoreController.class);

    @Autowired
    private RestoreTaskService restoreTaskService;

    @Autowired
    private DatabaseConfigService databaseConfigService;

    /**
     * Database restore list page
     */
    @GetMapping
    public String list(Model model) {
        List<RestoreTask> tasks = restoreTaskService.list();
        model.addAttribute("tasks", tasks);
        
        // Get databases for populating dropdown
        List<DatabaseConfig> databases = databaseConfigService.list();
        model.addAttribute("databases", databases);
        
        Map<Long, DatabaseConfig> databaseMap = new HashMap<>();
        for (DatabaseConfig db : databases) {
            databaseMap.put(db.getId(), db);
        }
        model.addAttribute("databaseMap", databaseMap);
        
        model.addAttribute("pageTitle", "同步平台 - 数据库恢复");
        return "restore/list";
    }

    /**
     * New restore task page
     */
    @GetMapping("/new")
    public String newTask(Model model) {
        List<DatabaseConfig> databases = databaseConfigService.list();
        model.addAttribute("databases", databases);
        model.addAttribute("task", new RestoreTask());
        model.addAttribute("pageTitle", "同步平台 - 新建恢复任务");
        return "restore/edit";
    }

    /**
     * Save restore task
     */
    @PostMapping("/save")
    @ResponseBody
    public Result<?> save(
            @RequestParam(required = false) Long id,
            @RequestParam String name,
            @RequestParam Long databaseId,
            @RequestParam(required = false) String description,
            @RequestParam(required = false) MultipartFile backupFile) {
        
        try {
            boolean success = restoreTaskService.saveRestoreTask(id, name, databaseId, description, backupFile);
            return success ? Result.success("保存成功") : Result.fail("保存失败");
        } catch (Exception e) {
            logger.error("Error saving restore task:", e);
            return Result.fail("保存失败: " + e.getMessage());
        }
    }

    /**
     * Execute restore task
     */
    @PostMapping("/execute/{id}")
    @ResponseBody
    public Result<?> execute(@PathVariable Long id) {
        try {
            Map<String, Object> result = restoreTaskService.executeTask(id);
            return (Boolean) result.get("success") ? 
                Result.success(result) : 
                Result.fail((String) result.get("message"));
        } catch (Exception e) {
            logger.error("Error executing restore task:", e);
            return Result.fail("执行恢复失败: " + e.getMessage());
        }
    }

    /**
     * Upload backup file
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result<?> uploadBackup(
            @RequestParam("file") MultipartFile file,
            @RequestParam("databaseId") Long databaseId) {
        
        try {
            String fileId = restoreTaskService.uploadBackupFile(file, databaseId);
            Map<String, Object> data = new HashMap<>();
            data.put("fileId", fileId);
            data.put("originalFilename", file.getOriginalFilename());
            return Result.success(data);
        } catch (Exception e) {
            logger.error("Error uploading backup file:", e);
            return Result.fail("上传备份文件失败: " + e.getMessage());
        }
    }

    /**
     * Delete restore task
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public Result<?> delete(@PathVariable Long id) {
        boolean success = restoreTaskService.removeById(id);
        return success ? Result.success() : Result.fail("删除失败");
    }

    /**
     * Get backup history
     */
    @GetMapping("/history/{databaseId}")
    @ResponseBody
    public Result<?> getBackupHistory(@PathVariable Long databaseId) {
        List<Map<String, Object>> history = restoreTaskService.getBackupHistory(databaseId);
        return Result.success(history);
    }
} 